package com.ruiyi.adrobot.web.controller.accountInfo;

import com.ruiyi.adrobot.beans.AccountInfo;
import com.ruiyi.adrobot.beans.Device;
import com.ruiyi.adrobot.beans.VirtualDevice;
import com.ruiyi.adrobot.beans.common.ResultMsg;
import com.ruiyi.adrobot.mongo.accountInfo.AccountInfoRepository;
import com.ruiyi.adrobot.mongo.device.DeviceRepository;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by tao.zeng on 2017/7/21.
 */
@Controller
@RequestMapping("/accountInfo")
public class AccountInfoController {
    @Autowired
    private AccountInfoRepository accountInfoRepository;
    @Autowired
    private DeviceRepository deviceRepository;
    @Value("${staticPath}")
    private String staticPath;

    @RequestMapping(value = "/toList", method = RequestMethod.GET)
    public String toList() {
        return "accountinfo/list";
    }

    @PostMapping("/addAccount")
    @ResponseBody
    public ResultMsg addAccount(@RequestParam(value = "account", required = true) MultipartFile file) {
        try {
            staticPath = staticPath + "/tmp/";
            if (!new File(staticPath).exists()) {
                new File(staticPath).mkdirs();
            }
            File newFile = new File(staticPath + "tem.xls");
            // 转存文件
            file.transferTo(newFile);
            FileInputStream inStream = new FileInputStream(newFile);
            Workbook workBook = WorkbookFactory.create(inStream);
            Sheet sheet = workBook.getSheetAt(0);
            // 为跳过第一行目录设置count
            // 跳过第一行的目录
            Device device;
            Integer fun;
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    continue;
                }
                AccountInfo.Account account = new AccountInfo.Account();
                if (null == row.getCell(0)) {
                    break;
                }
                row.getCell(1).setCellType(CellType.STRING);
                fun = Integer.valueOf(getCellValue(row.getCell(0)));
                account.setUserName(getCellValue(row.getCell(1)));
                account.setPwd(getCellValue(row.getCell(2)));
                account.setCreateDate(com.ruiyi.adrobot.utils.DateUtil.getCurrentTime());
                device = deviceRepository.findRandomDeviceByModelAndUsedFunsNot(null, fun);
                device.getUsedFuns().add(fun);
                deviceRepository.save(device);
                account.setImei(device.getImei());
                account.setModel(device.getModel());
                account.setVirtual(false);
                accountInfoRepository.appendAccount(fun, account);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultMsg.error("服务器端异常");
        }
        return ResultMsg.success();
    }

    //获取单元格的值
    private String getCellValue(Cell cell) {
        String cellValue = "";
        DataFormatter formatter = new DataFormatter();
        if (cell != null) {
            //判断单元格数据的类型，不同类型调用不同的方法
            switch (cell.getCellType()) {
                //数值类型
                case Cell.CELL_TYPE_NUMERIC:
                    //进一步判断 ，单元格格式是日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        cellValue = formatter.formatCellValue(cell);
                    } else {
                        //数值
                        double value = cell.getNumericCellValue();
                        int intValue = (int) value;
                        cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
                    }
                    break;
                case Cell.CELL_TYPE_STRING:
                    cellValue = cell.getStringCellValue();
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                //判断单元格是公式格式，需要做一种特殊处理来得到相应的值
                case Cell.CELL_TYPE_FORMULA: {
                    try {
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    } catch (IllegalStateException e) {
                        cellValue = String.valueOf(cell.getRichStringCellValue());
                    }

                }
                break;
                case Cell.CELL_TYPE_BLANK:
                    cellValue = "";
                    break;
                case Cell.CELL_TYPE_ERROR:
                    cellValue = "";
                    break;
                default:
                    cellValue = cell.toString().trim();
                    break;
            }
        }
        return cellValue.trim();
    }
}
